#include <func.h>

// 客户端
int main(void)
{
    int sock_fd = socket(AF_INET, SOCK_STREAM, 0);
    if(sock_fd == -1)
        error(1, errno, "socket");

    struct sockaddr_in addr;
    addr.sin_port = htons(atoi("8080"));
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    if(connect(sock_fd, (struct sockaddr*)&addr, sizeof(addr)) == -1)
        error(1, errno, "connect");

    int epoll_fd = epoll_create(1);
    if(epoll_fd == -1)
        error(1, errno, "epoll_create");
    struct epoll_event event;
    event.events = EPOLLIN;
    event.data.fd = sock_fd;
    epoll_ctl(epoll_fd, EPOLL_CTL_ADD, sock_fd, &event);
    event.data.fd = STDIN_FILENO;
    epoll_ctl(epoll_fd, EPOLL_CTL_ADD, STDIN_FILENO, &event);
    
    printf("开始聊天\n");
    while(1)
    {
        struct epoll_event event[2];
        int count = epoll_wait(epoll_fd, event, 2, -1);

        for(int i = 0; i < count; ++i)
        {
            char buf[128];
            int current_fd = event[i].data.fd;
            if(current_fd == STDIN_FILENO)
            {
                int ret = read(STDIN_FILENO, buf, 128);
                send(sock_fd, buf, ret, 0);
            }
            if(current_fd == sock_fd)
            {
                int ret = recv(sock_fd, buf, 128, 0);
                if(ret == 0)
                {
                    printf("已离开群聊，不要潜水\n");
                    _exit(1);
                }
                else
                    printf("other: %s\n", buf);
            }
        }
    }

    close(sock_fd);
    return 0;
}

